import React, { useEffect, useState } from "react";
import { MdEditor } from "md-editor-rt";
import "md-editor-rt/lib/style.css";
import { Input, Button, Form, Select, Switch, Radio } from "antd";
import { DownOutlined } from "@ant-design/icons";
import CommonPage from "@/components/page/CommonPage";
import CrudModal from "@/components/table/CrudModal";
import styled from "styled-components";
import Save2 from "@/components/svg/action-slot-icon/Save2";
import Public from "@/components/svg/action-slot-icon/Public";
import useMyContext from "@/hooks/useContext";
import UploadOne from "@/components/upload/UploadOne";
import { getCategoryOption } from "@/api/category";
import { getTagOption } from "@/api/tag";
import { articleTypeOptions } from "@/constant/data";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import nProgress from "nprogress";
import { getArticleById, saveOrUpdateArticle } from "@/api/article";
import action from "@/store/action";

const Styled = styled.div`
  header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .inp {
      width: 84%;
      margin-right: 15px;
    }
    .btn {
      flex: 1;
      justify-content: space-between;
      button {
        display: flex;
        align-items: center;
      }
    }
  }
`;
const MAX_COUNT = 3;

const Write = (props) => {
  const params = useParams();
  const location = useLocation();
  const navigate = useNavigate();
  const { messageApi } = useMyContext();

  //保存和发布按钮loading
  const [loading, setLoading] = useState(false);
  //输入标题
  const [title, setTitle] = useState("");
  //富文本编辑
  const [content, setContent] = useState("hello md-editor-rt！");

  // modal控制显示和隐藏
  const [modalVisible, setModalVisible] = useState(false);

  //表格相关的数据
  const [formIns] = Form.useForm();
  const [categoryOptions, setCategoryOptions] = useState([]); // 分类选项
  const [tagOptions, setTagOptions] = useState([]); // 标签选项
  const [formModel, setFormModel] = useState({
    is_top: 0,
    status: 1,
  });
  //收集标签的数组
  const [SelectTagValue, setSelectTagValue] = useState([]);
  function UpdateFormModel(nVal) {
    setFormModel({ ...formModel, ...nVal });
  }

  function handleDraft() {
    //保持草稿
    messageApi.info("保存草稿开发中");
  }
  function handlePublish() {
    //发布功能
    // 判断标题是否存在
    if (title.trim() === "" || title === "") {
      // 清空输入内容
      setTitle("");
      messageApi.info("请输入标题");
      return;
    }
    //打开模型层
    setModalVisible(true);
  }
  //编辑完毕函数
  async function handleSave() {
    //modal点击确定的回调

    try {
      await formIns.validateFields();
      // 设置loading
      setLoading(true);
      messageApi.open({
        type: "loading",
        content: "正在保存...",
        key: "loading",
      });
      //获取表单的值
      const val = formIns.getFieldsValue();
      //添加标题和内容
      val.title = title;
      val.content = content;
      val.img = formModel.img;
      // 将收集到的标签值map为标签名
      categoryOptions.forEach((item) => {
        if (item.value === val.category_name) {
          val.category_name = item.label;
        }
      });

      val.tag_names.forEach((tag, i) => {
        tagOptions.forEach((item, ii) => {
          //tag为 1 2 3对于value值，map为label
          if (item.value === tag) {
            val.tag_names[i] = item.label;
          }
        });
      });
      if (params?.id) {
        //代表是编辑，传入编辑文章的id
        val.id = params.id;
      }
      //调用接口更新
      const { code, message } = await saveOrUpdateArticle(val);
      messageApi.destroy("loading");
      if (+code === 1206) {
        messageApi.warning(message);
        return;
      }
      messageApi.open({
        type: "success",
        content: "保存成功",
      });

      //清除当前标签
      action.tags.removeTag(location.pathname);
      navigate({ pathname: "/article/list" }, { replace: true });
    } catch (error) {
      console.log(error);
      messageApi.open({
        type: "error",
        content: "保存失败",
      });
    } finally {
      setLoading(false);
      //关闭弹窗
      setModalVisible(false);
    }
  }

  async function getArticleInfo() {
    //如果是编辑，即路由带参数，获取当前编号信息
    const id = params?.id;
    if (!id) {
      //无文章id，表示为新增文章
      return;
    }
    try {
      messageApi.open({
        type: "loading",
        content: "加载中...",
        key: "loading",
      });
      const res = await getArticleById(id);
      UpdateFormModel({ ...res.data });
      //回调文章标签，因为标签是单独数组保存
      setSelectTagValue(res.data.tag_names);
      //设置文章标题
      setTitle(res.data.title);
      //设置富文本内容
      setContent(res.data.content);
      messageApi.destroy("loading");
      messageApi.open({
        type: "success",
        content: "加载成功.",
      });
    } catch (error) {
      messageApi.open({
        type: "error",
        content: "加载失败...",
      });
    }
  }

  useEffect(() => {
    //获取分类和标签数据
    getCategoryOption().then((res) => {
      setCategoryOptions(res.data);
    });
    getTagOption().then((res) => {
      setTagOptions(res.data);
    });
    getArticleInfo();
  }, []);

  return (
    <Styled>
      <CommonPage showHeader={false}>
        <header>
          <div className="inp">
            <Input
              placeholder="输入文字标题..."
              style={{ height: "44px" }}
              value={title}
              onChange={(e) => {
                setTitle(e.target.value);
              }}
            ></Input>
          </div>
          <div className="btn flex">
            <Button
              danger
              icon={<Save2></Save2>}
              onClick={handleDraft}
              loading={loading}
            >
              保存草稿
            </Button>
            <Button
              danger
              type="primary"
              icon={<Public />}
              loading={loading}
              onClick={handlePublish}
            >
              发布文章
            </Button>
          </div>
        </header>
        {/* 富文本编辑器 */}
        <MdEditor
          modelValue={content}
          onChange={setContent}
          style={{ height: "calc(100vh - 360px)" }}
        />
        <CrudModal
          visible={modalVisible}
          handleSave={handleSave}
          setModalVisible={setModalVisible}
          loading={loading}
          title="发布文章"
          clearFormFields={() => formIns.resetFields()}
        >
          <Form
            form={formIns}
            name="article-write"
            labelAlign="left"
            className="my-form"
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 20,
            }}
            initialValues={{
              is_top: 0,
              status: 1,
              ...formModel,
            }}
          >
            <Form.Item
              label="文章分类"
              name="category_name"
              validateTrigger={["onBlur", "onChange"]}
              rules={[
                {
                  required: true,
                  message: "请选择文章分类",
                },
              ]}
            >
              <Select
                style={{ width: "70%" }}
                placeholder="关键字搜索，enter添加"
                allowClear
                options={categoryOptions}
                defaultValue={[formModel.category_name]}
              ></Select>
            </Form.Item>
            <Form.Item
              label="文章标签"
              name="tag_names"
              validateTrigger={["onBlur", "onChange"]}
              rules={[{ required: true, message: "请选择文章标签" }]}
            >
              <Select
                mode="multiple"
                // maxCount={MAX_COUNT}
                value={SelectTagValue}
                style={{
                  width: "100%",
                }}
                onChange={setSelectTagValue}
                suffixIcon={
                  <>
                    <span>
                      {SelectTagValue.length} / {MAX_COUNT}
                    </span>
                    <DownOutlined />
                  </>
                }
                placeholder="请选择标签"
                options={tagOptions}
                defaultValue={formModel.tag_names}
              />
            </Form.Item>
            <Form.Item
              label="文章类型"
              name="type"
              rules={[{ required: true, message: "请选择文章分类" }]}
            >
              <Select
                style={{ width: "50%" }}
                placeholder="请选择文章分类"
                allowClear
                options={articleTypeOptions}
                onChange={(val) => {
                  UpdateFormModel({ type: val });
                }}
                defaultValue={[formModel.type]}
              ></Select>
            </Form.Item>
            {/* 根据选择的文章类型，如果非原创就需要填写链接 */}
            {formModel.type === 2 || formModel.type === 3 ? (
              <Form.Item label="原文地址" name="original_url">
                <Input placeholder="请填写原文链接" />
              </Form.Item>
            ) : null}
            <Form.Item label="文章缩略图">
              <UploadOne
                width={220}
                preview={formModel.img}
                UpdateFormModel={UpdateFormModel}
              />
            </Form.Item>
            <Form.Item
              label="置顶"
              name="is_top"
              rules={[{ required: true, message: "请选择是否置顶" }]}
            >
              <Switch defaultChecked={formModel.is_top ? true : false} />
            </Form.Item>
            <Form.Item
              label="发布形式"
              name="status"
              rules={[{ required: true, message: "请选择发布形式" }]}
            >
              <Radio.Group>
                <Radio value={1}>公开</Radio>
                <Radio value={2}>私密</Radio>
              </Radio.Group>
            </Form.Item>
          </Form>
        </CrudModal>
      </CommonPage>
    </Styled>
  );
};

export default Write;
